<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use ba\Filesystem;
use hehe\Str;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Db;

/**
 * 商品管理
 */
class Goods extends Backend {
    /**
     * Goods模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Goods
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['name'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\admin\model\goods\Goods;
    }

    public function collection(): void {
        $goods_id = $this->request->param('goods_id');
        $admin_id = $this->auth->id;

        $where = [
            'goods_id' => $goods_id,
            'admin_id' => $admin_id,
            'outstation_id' => $this->outstation['id']
        ];
        if(Db::name('goods_collection')->where($where)->find()){
            $this->success();
        }
        $insert = $where;
        $insert['create_time'] = $this->timestamp;
        $result = db::name('goods_collection')->insert($insert);
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }
    public function cancelCollection(): void {
        $goods_id = $this->request->param('goods_id');
        $admin_id = $this->auth->id;
        $where = [
            'goods_id' => $goods_id,
            'outstation_id' => $this->outstation['id']
        ];
        $row = Db::name('goods_collection')->where($where)->find();
        if(!$row){
            $this->success();
        }

        $result = db::name('goods_collection')->where(['id' => $row['id']])->delete();
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 季度编码列表
     */
    public function quarterCodeList(){
        $param = $this->request->param();
        list($where, $alias, $limit, $order) = $this->queryBuilder();

        if(empty($param['user_id'])) {
            $this->error('请选择用户', [
                'list' => [],
                'total' => 0
            ]);
        }
        if(empty($param['brand_id'])) $this->error('请选择品牌');

        $base_where = [
            ['outstation_id', '=', $this->outstation['id']],
            ['quarter_code', '<>', ''],
        ];
        if(!empty($param['brand_id'])){
            $base_where[] = ['goods_brand_id', '=', $param['brand_id']];
        }

//        print_r($base_where);die;

        $res = $this->model->field($this->indexField)->alias('goods')->where($where)->where($base_where)->whereNotNull('quarter_code')->group('quarter_code')->order($order)->paginate($limit);
        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total()
        ]);
    }


    /**
     * 商品列表
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $show_goods = $this->request->has('show_goods') ? $this->request->param('show_goods') : 'all';
        $brand_id = $this->request->has('brand_id') ? $this->request->param('brand_id') : 0;
        $param = $this->request->param();
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        if($show_goods == 'collection'){
            $collectionModel = new \app\admin\model\goods\Collection;
            # 查询本站收藏的商品记录
            if($brand_id){
                $res = $collectionModel
                    ->withJoin(['goods' => function($query) use ($brand_id){
                        $query->with(['specs'])->where(['goods_brand_id' => $brand_id]);
                        $query->where(['goods.outstation_id' => $this->outstation['id']]);
                    }], 'LEFT')->group('goods_id')
                    ->alias($alias)
                    ->where($where)
                    ->where(['collection.outstation_id' => $this->outstation['id']])
                    ->order($order)
                    ->paginate($limit);
            }else{
                $res = $collectionModel
                    ->withJoin(['goods' => function($query) use ($brand_id){
                        $query->with(['specs'])->where(['goods.outstation_id' => $this->outstation['id']]);
                    }], 'LEFT')->group('goods_id')
                    ->alias($alias)
                    ->where($where)
                    ->where(['collection.outstation_id' => $this->outstation['id']])
                    ->order($order)
                    ->paginate($limit);
            }


            $list = [];
            $goods_list = $res->items();
            foreach($goods_list as $val){
                $val['goods']['brand'] = $val['brand'];
                $val['goods']['specs'] = $val['specs'];
                $list[] = $val['goods'];
            }

        }else{
            $base_where = [
                ['goods.outstation_id', '=', $this->outstation['id']],
            ];
            if(!empty($param['brand_id'])) {
                $base_where[] = ['goods.goods_brand_id', '=', $param['brand_id']];
            }
            if(!empty($param['quarter_code'])) {
                $base_where[] = ['goods.quarter_code', '=', $param['quarter_code']];
            }
            // 商品主表关联 -> 表：品牌，收藏
            $res = $this->model->field($this->indexField)->with(['specs', 'brand', 'collection' => function($query){
                $query->where(['outstation_id' => $this->outstation['id']]);
            }])->alias('goods')->where($where)->where($base_where);


            $res = $res->order($order)->paginate($limit);

            $list = $res->items();

        }

        foreach ($list as $key => $val) {
            $list[$key]['price'] = number_format($val['price'], 0, '.', ',');
            $list[$key]['supply_price'] = number_format($val['supply_price'], 0, '.', ',');
            $size = empty($val['size']) ? [] : explode(',', $val['size']);
            $stock = empty($val['stock']) ? [] : explode(',', $val['stock']);

            $sizeWithStock = [];
            for ($i = 0; $i < 4; $i++) {
                $sizeWithStock[] = [
                    'size' => empty($size[$i]) || $size[$i] == 'TOTAL' ? '&nbsp;' : $size[$i],
                    'stock' => empty($stock[$i]) || $i + 1 == count($stock) ? '&nbsp;' : $stock[$i],
                ];
            }
            $sizeWithStock[] = [
                'size' => empty($size[count($size) - 1]) ? ' ' : $size[count($size) - 1],
                'stock' => empty($stock[count($stock) - 1]) ? ' ' : $stock[count($stock) - 1]
            ];
            $list[$key]['size_with_stock'] = $sizeWithStock;
        }

        $this->success('', [
            'list' => $list,
            'total' => isset($total) ? $total : $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    public function import(): void {
        $params = $this->request->post();

        if ($params['goods_brand_id'] == 0) $this->error('请选择品牌');
        if (empty($params['file'])) $this->error('请上传文件');
        if (empty($params['quarter_code'])) $this->error('请填写季度编码');

        $attachment = Db::name('attachment')->where(['url' => $params['file']])->find();

        // 读取xls文件内容
        $filePath = Filesystem::fsFit(public_path() . $params['file']);
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getSheet(0);
        $data = $sheet->toArray(); // 获取表格中的文字内容
        $allImage = $sheet->getDrawingCollection(); // 获取表格中的图片内容
        $images = [];
        if ($allImage) {

            foreach ($allImage as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $filename = $drawing->getPath();
                $info = explode('/', $filename);
                $image_name = md5($this->timestamp . mt_rand(10000, 99999)) . '_' . $info[count($info) - 1];
                $date = date('Ymd');
                $image_dir = Filesystem::fsFit('storage/import_xlsx_images/' . $date . '/');
                $image_path = Filesystem::fsFit(public_path() . $image_dir);

                if (!file_exists($image_path)) {
                    Filesystem::mkdir($image_path);
                }
                copy($filename, $image_path . $image_name);
                $startColumn = Str::letterToDigit($startColumn);
                $tempRow = $startRow - 1;
                $images[$tempRow][$startColumn] = '/storage/import_xlsx_images/' . $date . '/' . $image_name;
            }
        }

        foreach ($images as $key => $val) {
            foreach ($val as $k => $v) {
                if (empty($data[$key][$k])) $data[$key][$k] = $v;
            }
        }

        foreach ($data as $key => $val) $data[$key] = array_filter($val);

        $insert = [];
        $j = 0;
        $data = array_filter($data);
//        print_r($data);die;
        foreach ($data as $val) {
            try {
                if (strstr($val[0], '품명')) {
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $insert[$j][$l]['name'] = $v;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '이미지')) { // 商品图片
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $insert[$j][$l]['image'] = $v;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '컬러')) { // 颜色
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $insert[$j][$l]['color'] = $v;
                            $l++;

                        }
                    }
                }
                if (strstr($val[0], '사이즈')) { // 尺码
                    $l = 0;
                    $c = 0;
                    $count = (count($val) - 1) / 5;
                    $size = $val;
                    foreach ($val as $k => $v) {
                        if ($k <= 0) continue;
                        $insert[$j][$l]['size'][] = $v;
                        $c++;
                        if ($c >= $count) {
                            $l++;
                            $c = 0;
                        }
                    }
                }
                if (strstr($val[0], '재고')) { // 库存
                    $l = 0;
                    $c = 0;
                    $count = (count($size) - 1) / 5;
                    foreach ($size as $k => $v) {
                        if ($k <= 0) continue;
                        if (empty($val[$k])) {
                            $insert[$j][$l]['stock'][] = '';
                        } else {
                            $insert[$j][$l]['stock'][] = $val[$k];
                        }
                        $c++;
                        if ($c >= $count) {
                            $l++;
                            $c = 0;
                        }
                    }
                }
                if (strstr($val[0], '소비자가')) { // 售价
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $price = str_replace(['₩', ','], '', $v);
                            $insert[$j][$l]['price'] = $price;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '공급가율(%)')) { // 供货折扣
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $discount = str_replace(['%'], '', $v);
                            $insert[$j][$l]['supply_discount'] = $discount;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '공급가')) { // 供货价格
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $price = str_replace(['₩', ','], '', $v);
                            $insert[$j][$l]['supply_price'] = $price;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '15일')) { // 生产周期 15天
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $insert[$j][$l]['cycle_15'] = $v;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '30일')) { // 生产周期30天
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $insert[$j][$l]['cycle_30'] = $v;
                            $l++;
                        }
                    }
                }
                if (strstr($val[0], '링크')) { // 上游链接
                    $l = 0;
                    foreach ($val as $k => $v) {
                        if ($k > 0) {
                            $insert[$j][$l]['upstream_link'] = $v;
                            $l++;
                        }
                    }
                    $j++;
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage() . ' ---' . $e->getLine());
            }
        }
//        print_r($insert);die;
        $goods_import_insert = [
            'file_name' => $attachment['name'],
            'create_time' => $this->timestamp
        ];
        Db::startTrans();
        try{
            $goods_import_id = Db::name('goods_import')->insertGetId($goods_import_insert);
            foreach ($insert as $key => $val) {
                foreach ($val as $k => $v) {
                    $row = $v;
                    if (empty($v['image'])) {
                        $row['cover'] = '';
                    } else {
                        $row['cover'] = $v['image'];
                        unset($row['image']);
                    }
                    $row = array_filter($row);
                    $row['create_time'] = $this->timestamp;
                    $row['goods_brand_id'] = $params['goods_brand_id'];
                    $row['outstation_id'] = $this->outstation['id'];
                    $row['goods_import_id'] = $goods_import_id;
                    $row['quarter_code'] = $params['quarter_code']; // 季度编码

                    if(isset($row['color'])) unset($row['color']);

                    unset($row['size']);
                    unset($row['stock']);
                    $goods_id = Db::name('goods')->insertGetId($row);
                    $specs = [];
                    if($v['size']){
                        foreach($v['size'] as $sk => $sv){
                            if(strtolower(trim($sv)) == 'total') continue;
                            $specs[] = [
                                'goods_id' => $goods_id,
                                'color' => empty($v['color']) ? null : $v['color'],
                                'size' => $sv,
                                'stock' => empty($v['stock'][$sk]) ? 0 : (int)$v['stock'][$sk]
                            ];
                        }
                    }
//                    print_r($specs);die;
                    if($specs){
                        Db::name('goods_specs')->insertAll($specs);
                    }

                }
            }
            db::commit();
        }catch(\Exception $e){
            db::rollback();
            $this->error($e->getMessage());
        }



        $this->success();

    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */


    public function demo() {
        $zip = new ZipArchive;
        $filename = 'path/to/excel/file.xlsx';

        if ($zip->open($filename) === true) {
            // 遍历所有文件
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $entryName = $zip->getNameIndex($i);

                // 判断文件是否为图片
                if (strpos($entryName, 'xl/media/') === 0 && preg_match('/\.(jpg|jpeg|png|gif)$/', $entryName)) {
                    // 获取图片文件的内容
                    $imageData = $zip->getFromName($entryName);

                    // 生成一个唯一的文件名
                    $fileName = uniqid() . '.' . pathinfo($entryName, PATHINFO_EXTENSION);

                    // 保存图片到指定目录
                    $destination = 'path/to/save/images/' . $fileName;
                    file_put_contents($destination, $imageData);

                    // 输出图片路径
                    echo 'Image saved: ' . $destination . '<br>';
                }
            }

            $zip->close();
        } else {
            echo 'Failed to open the file.';
        }
    }


}